<template>
  <div class="family-tree-view">
    <div class="view-header">
      <h2>家族族谱管理</h2>
      <div class="header-actions">
        <button v-if="auth.role === 'admin'" @click="showAddForm = true" class="btn primary">
          <span>➕</span> 添加成员
        </button>
        <button @click="refreshData" class="btn secondary">
          <span>🔄</span> 刷新
        </button>
        <button v-if="auth.role === 'admin'" @click="showRecycleBin = true" class="btn danger">
          <span>🗑️</span> 回收站
        </button>
      </div>
    </div>
    
    <div class="view-tabs">
      <button 
        v-for="tab in tabs" 
        :key="tab.id"
        @click="activeTab = tab.id"
        :class="['tab-btn', { active: activeTab === tab.id }]"
      >
        {{ tab.label }}
      </button>
    </div>
    
    <div class="view-content">
      <!-- 成员列表视图 -->
      <div v-if="activeTab === 'list'" class="list-view">
        <div class="list-header">
          <div class="search-filter">
            <div class="basic-search">
              <input 
                v-model="searchKeyword" 
                @input="filterMembers"
                placeholder="搜索成员姓名、职业、地址..."
                class="search-input"
              >
              <select v-model="filterGeneration" @change="filterMembers" class="filter-select">
                <option value="">所有世代</option>
                <option v-for="gen in availableGenerations" :key="gen" :value="gen">
                  {{ gen }}代
                </option>
              </select>
              <select v-model="filterGender" @change="filterMembers" class="filter-select">
                <option value="">所有性别</option>
                <option value="男">男性</option>
                <option value="女">女性</option>
              </select>
            </div>
            
            <!-- 高级筛选 -->
            <div class="advanced-filters" v-if="showAdvancedFilters">
              <div class="filter-row">
                <div class="filter-group">
                  <label>职业筛选：</label>
                  <select v-model="filterOccupation" @change="filterMembers" class="filter-select">
                    <option value="">所有职业</option>
                    <option v-for="occupation in availableOccupations" :key="occupation" :value="occupation">
                      {{ occupation }}
                    </option>
                  </select>
                </div>
                <div class="filter-group">
                  <label>婚姻状态：</label>
                  <select v-model="filterMaritalStatus" @change="filterMembers" class="filter-select">
                    <option value="">所有状态</option>
                    <option value="未婚">未婚</option>
                    <option value="已婚">已婚</option>
                    <option value="离异">离异</option>
                    <option value="丧偶">丧偶</option>
                  </select>
                </div>
              </div>
              <div class="filter-row">
                <div class="filter-group">
                  <label>年龄范围：</label>
                  <input 
                    v-model.number="filterAgeMin" 
                    @input="filterMembers"
                    type="number" 
                    placeholder="最小年龄" 
                    class="age-input"
                  >
                  <span>-</span>
                  <input 
                    v-model.number="filterAgeMax" 
                    @input="filterMembers"
                    type="number" 
                    placeholder="最大年龄" 
                    class="age-input"
                  >
                </div>
                <div class="filter-group">
                  <label>教育程度：</label>
                  <select v-model="filterEducation" @change="filterMembers" class="filter-select">
                    <option value="">所有教育程度</option>
                    <option v-for="education in availableEducations" :key="education" :value="education">
                      {{ education }}
                    </option>
                  </select>
                </div>
              </div>
            </div>
            
            <div class="filter-controls">
              <button @click="toggleAdvancedFilters" class="btn btn-sm">
                {{ showAdvancedFilters ? '收起高级筛选' : '展开高级筛选' }}
              </button>
              <button @click="clearAllFilters" class="btn btn-sm btn-secondary">
                清除筛选
              </button>
            </div>
          </div>
          <div class="list-actions">
            <span class="member-count">共 {{ filteredMembers.length }} 个成员</span>
          </div>
        </div>
        
        <div class="members-grid">
          <div 
            v-for="member in filteredMembers" 
            :key="member.id"
            class="member-card"
            @click="selectMember(member)"
          >
            <div class="member-avatar" :class="`gender-${member.gender}`">
              <span>{{ member.name.charAt(0) }}</span>
            </div>
            <div class="member-info">
              <h3 class="member-name">{{ member.name }} (ID:{{ member.id }})</h3>
              <p class="member-details">
                <span class="gender">{{ member.gender }}</span>
                <span v-if="member.generation" class="generation">{{ member.generation }}代</span>
                <span v-if="member.birthDate" class="birth-date">
                  {{ formatDate(member.birthDate) }}
                </span>
              </p>
              <p v-if="member.spouse" class="spouse-info">
                <span class="label">配偶：</span>
                <span class="spouse-name">{{ member.spouse.name }}</span>
              </p>
              <p v-if="member.childrenCount > 0" class="children-info">
                <span class="label">子女：</span>
                <span class="children-count">{{ member.childrenCount }}人</span>
              </p>
              <p v-if="member.occupation" class="occupation">{{ member.occupation }}</p>
              <p v-if="member.description" class="description">{{ member.description }}</p>
            </div>
            <div class="member-actions">
              <button v-if="auth.role === 'admin'" @click.stop="editMember(member)" class="action-btn edit">✏️</button>
              <button v-if="auth.role === 'admin'" @click.stop="deleteMember(member)" class="action-btn delete">🗑️</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 家族树视图 -->
      <div v-else-if="activeTab === 'tree'" class="tree-view">
        <FamilyTree 
          :members="members" 
          @select-member="selectMember"
          @edit-member="editMember"
        />
      </div>
      
      <!-- 统计面板 -->
      <div v-else-if="activeTab === 'stats'" class="stats-view">
        <FamilyStats :members="members" />
      </div>
    </div>
    
    <!-- 添加/编辑成员表单 -->
    <AddMemberForm
      v-if="showAddForm"
      :member="editingMember"
      :members="members"
      :visible="showAddForm"
      :is-editing="!!editingMember"
      @save="handleSaveMember"
      @close="closeForm"
      @error="handleError"
    />
    
    <!-- 成员详情弹窗 -->
    <div v-if="selectedMember" class="modal-overlay" @click="closeDetail">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ selectedMember.name }} (ID:{{ selectedMember.id }}) 的详细信息</h3>
          <button @click="closeDetail" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <!-- 详情标签页 -->
          <div class="detail-tabs">
            <button 
              v-for="tab in detailTabs" 
              :key="tab.id"
              @click="activeDetailTab = tab.id"
              :class="['tab-btn', { active: activeDetailTab === tab.id }]"
            >
              {{ tab.label }}
            </button>
          </div>
          
          <!-- 基本信息 -->
          <div v-if="activeDetailTab === 'basic'" class="detail-content">
            <div class="member-detail-grid">
              <div class="detail-item">
                <label>姓名：</label>
                <span>{{ selectedMember.name }}</span>
              </div>
              <div class="detail-item">
                <label>性别：</label>
                <span>{{ selectedMember.gender }}</span>
              </div>
              <div class="detail-item">
                <label>世代：</label>
                <span>{{ selectedMember.generation ? `第${selectedMember.generation}代` : '第1代' }}</span>
              </div>
              <div class="detail-item">
                <label>出生日期：</label>
                <span>{{ formatDate(selectedMember.birthDate) }}</span>
              </div>
              <div class="detail-item">
                <label>职业：</label>
                <span>{{ selectedMember.occupation || '未填写' }}</span>
              </div>
              <div class="detail-item">
                <label>地址：</label>
                <span>{{ selectedMember.address || '未填写' }}</span>
              </div>
              <div class="detail-item">
                <label>教育程度：</label>
                <span>{{ selectedMember.education || '未填写' }}</span>
              </div>
              <div class="detail-item">
                <label>婚姻状态：</label>
                <span>{{ selectedMember.maritalStatus || '未填写' }}</span>
              </div>
              <div class="detail-item full-width">
                <label>描述：</label>
                <p>{{ selectedMember.description || '暂无描述' }}</p>
              </div>
            </div>
          </div>
          
          <!-- 家庭关系 -->
          <div v-if="activeDetailTab === 'family'" class="detail-content">
            <div class="family-relations">
              <!-- 父母 -->
              <div v-if="relatives.parents && relatives.parents.length" class="relation-group">
                <h4>父母</h4>
                <div class="relation-list">
                  <div v-for="parent in relatives.parents" :key="parent.id" class="relation-item" @click="selectMember(parent)">
                    <div class="member-avatar" :class="parent.gender">{{ parent.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ parent.name }} (ID:{{ parent.id }})</div>
                      <div class="relation-detail">{{ parent.gender }} · {{ parent.generation ? `第${parent.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 配偶 -->
              <div v-if="relatives.spouses && relatives.spouses.length" class="relation-group">
                <h4>配偶</h4>
                <div class="relation-list">
                  <div v-for="spouse in relatives.spouses" :key="spouse.id" class="relation-item" @click="selectMember(spouse)">
                    <div class="member-avatar" :class="spouse.gender">{{ spouse.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ spouse.name }} (ID:{{ spouse.id }})</div>
                      <div class="relation-detail">{{ spouse.gender }} · {{ spouse.generation ? `第${spouse.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 子女 -->
              <div v-if="relatives.children && relatives.children.length" class="relation-group">
                <h4>子女 ({{ relatives.children.length }}人)</h4>
                <div class="relation-list">
                  <div v-for="child in relatives.children" :key="child.id" class="relation-item" @click="selectMember(child)">
                    <div class="member-avatar" :class="child.gender">{{ child.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ child.name }} (ID:{{ child.id }})</div>
                      <div class="relation-detail">{{ child.gender }} · {{ child.generation ? `第${child.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 兄弟姐妹 -->
              <div v-if="relatives.siblings && relatives.siblings.length" class="relation-group">
                <h4>兄弟姐妹 ({{ relatives.siblings.length }}人)</h4>
                <div class="relation-list">
                  <div v-for="sibling in relatives.siblings" :key="sibling.id" class="relation-item" @click="selectMember(sibling)">
                    <div class="member-avatar" :class="sibling.gender">{{ sibling.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ sibling.name }} (ID:{{ sibling.id }})</div>
                      <div class="relation-detail">{{ sibling.gender }} · {{ sibling.generation ? `第${sibling.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 祖父母 -->
              <div v-if="relatives.grandparents && relatives.grandparents.length" class="relation-group">
                <h4>祖父母</h4>
                <div class="relation-list">
                  <div v-for="gp in relatives.grandparents" :key="gp.id" class="relation-item" @click="selectMember(gp)">
                    <div class="member-avatar" :class="gp.gender">{{ gp.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ gp.name }} (ID:{{ gp.id }})</div>
                      <div class="relation-detail">{{ gp.gender }} · {{ gp.generation ? `第${gp.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 堂兄弟姐妹 -->
              <div v-if="relatives.paternalCousins && relatives.paternalCousins.length" class="relation-group">
                <h4>堂兄弟姐妹</h4>
                <div class="relation-list">
                  <div v-for="cousin in relatives.paternalCousins" :key="cousin.id" class="relation-item" @click="selectMember(cousin)">
                    <div class="member-avatar" :class="cousin.gender">{{ cousin.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ cousin.name }} (ID:{{ cousin.id }})</div>
                      <div class="relation-detail">{{ cousin.gender }} · {{ cousin.generation ? `第${cousin.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 表兄弟姐妹 -->
              <div v-if="relatives.maternalCousins && relatives.maternalCousins.length" class="relation-group">
                <h4>表兄弟姐妹</h4>
                <div class="relation-list">
                  <div v-for="cousin in relatives.maternalCousins" :key="cousin.id" class="relation-item" @click="selectMember(cousin)">
                    <div class="member-avatar" :class="cousin.gender">{{ cousin.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ cousin.name }} (ID:{{ cousin.id }})</div>
                      <div class="relation-detail">{{ cousin.gender }} · {{ cousin.generation ? `第${cousin.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 继父母/养父母 -->
              <div v-if="relatives.stepParents && relatives.stepParents.length" class="relation-group">
                <h4>继父母/养父母</h4>
                <div class="relation-list">
                  <div v-for="sp in relatives.stepParents" :key="sp.id" class="relation-item" @click="selectMember(sp)">
                    <div class="member-avatar" :class="sp.gender">{{ sp.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ sp.name }} (ID:{{ sp.id }})</div>
                      <div class="relation-detail">{{ sp.gender }} · {{ sp.generation ? `第${sp.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 继兄弟姐妹/养兄弟姐妹 -->
              <div v-if="relatives.stepSiblings && relatives.stepSiblings.length" class="relation-group">
                <h4>继兄弟姐妹/养兄弟姐妹</h4>
                <div class="relation-list">
                  <div v-for="ss in relatives.stepSiblings" :key="ss.id" class="relation-item" @click="selectMember(ss)">
                    <div class="member-avatar" :class="ss.gender">{{ ss.name.charAt(0) }}</div>
                    <div class="relation-info">
                      <div class="relation-name">{{ ss.name }} (ID:{{ ss.id }})</div>
                      <div class="relation-detail">{{ ss.gender }} · {{ ss.generation ? `第${ss.generation}代` : '第1代' }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 照片管理 -->
          <div v-if="activeDetailTab === 'photos'" class="detail-content">
            <PhotoManager 
              :member="selectedMember" 
              @update-photos="updateMemberPhotos"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 回收站弹窗 -->
    <div v-if="showRecycleBin" class="modal-overlay" @click="showRecycleBin = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>回收站（已删除成员）</h3>
          <button @click="showRecycleBin = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div v-if="recycleBinLoading">加载中...</div>
          <div v-else>
            <div v-if="deletedMembers.length === 0">暂无已删除成员</div>
            <ul v-else class="recycle-list">
              <li v-for="member in deletedMembers" :key="member.id" class="recycle-item">
                <span>{{ member.name }} (ID:{{ member.id }})</span>
                <button class="btn restore" @click="restoreDeletedMember(member)">恢复</button>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import AddMemberForm from '@/components/AddMemberForm.vue';
import FamilyTree from '@/components/FamilyTree.vue';
import FamilyStats from '@/components/FamilyStats.vue';
import PhotoManager from '@/components/PhotoManager.vue';
import { getPersons, getPersonById, createPerson, updatePerson, deletePerson, getRelatives, getDeletedPersons, restorePerson } from '@/services/person.service.js';
import { useAuthStore } from '../stores/auth';

export default {
  name: 'FamilyTreeView',
  components: {
    AddMemberForm,
    FamilyTree,
    FamilyStats,
    PhotoManager
  },
  setup() {
    // 状态
    const members = ref([]);
    const loading = ref(false);
    const showAddForm = ref(false);
    const editingMember = ref(null);
    const selectedMember = ref(null);
    const activeTab = ref('list');
    const activeDetailTab = ref('basic');
    
    // 搜索和筛选
    const searchKeyword = ref('');
    const filterGeneration = ref('');
    const filterGender = ref('');
    const showAdvancedFilters = ref(false);
    const filterOccupation = ref('');
    const filterMaritalStatus = ref('');
    const filterAgeMin = ref(null);
    const filterAgeMax = ref(null);
    const filterEducation = ref('');
    
    // 标签页配置
    const tabs = [
      { id: 'list', label: '成员列表', icon: '📋' },
      { id: 'tree', label: '家族树', icon: '🌳' },
      { id: 'stats', label: '统计面板', icon: '📊' }
    ];
    
    // 详情标签页配置
    const detailTabs = [
      { id: 'basic', label: '基本信息' },
      { id: 'family', label: '家庭关系' },
      { id: 'photos', label: '照片管理' }
    ];
    
    // 计算属性
    const availableGenerations = computed(() => {
      const gens = [...new Set(members.value.map(m => m.generation).filter(Boolean))];
      return gens.sort((a, b) => a - b);
    });
    
    const availableOccupations = computed(() => {
      const occupations = [...new Set(members.value.map(m => m.occupation).filter(Boolean))];
      return occupations.sort();
    });
    
    const availableEducations = computed(() => {
      const educations = [...new Set(members.value.map(m => m.education).filter(Boolean))];
      return educations.sort();
    });
    
    // 计算年龄
    const calculateAge = (birthDate) => {
      if (!birthDate) return null;
      const today = new Date();
      const birth = new Date(birthDate);
      let age = today.getFullYear() - birth.getFullYear();
      const monthDiff = today.getMonth() - birth.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
      }
      return age;
    };
    
    const filteredMembers = computed(() => {
      let filtered = members.value;
      
      // 基本搜索
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        filtered = filtered.filter(member => 
          member.name.toLowerCase().includes(keyword) ||
          (member.occupation && member.occupation.toLowerCase().includes(keyword)) ||
          (member.address && member.address.toLowerCase().includes(keyword)) ||
          (member.description && member.description.toLowerCase().includes(keyword))
        );
      }
      
      // 世代筛选
      if (filterGeneration.value) {
        filtered = filtered.filter(member => member.generation == filterGeneration.value);
      }
      
      // 性别筛选
      if (filterGender.value) {
        filtered = filtered.filter(member => member.gender === filterGender.value);
      }
      
      // 职业筛选
      if (filterOccupation.value) {
        filtered = filtered.filter(member => member.occupation === filterOccupation.value);
      }
      
      // 婚姻状态筛选
      if (filterMaritalStatus.value) {
        filtered = filtered.filter(member => member.maritalStatus === filterMaritalStatus.value);
      }
      
      // 年龄范围筛选
      if (filterAgeMin.value !== null || filterAgeMax.value !== null) {
        filtered = filtered.filter(member => {
          const age = calculateAge(member.birthDate);
          if (age === null) return false;
          
          if (filterAgeMin.value !== null && age < filterAgeMin.value) return false;
          if (filterAgeMax.value !== null && age > filterAgeMax.value) return false;
          return true;
        });
      }
      
      // 教育程度筛选
      if (filterEducation.value) {
        filtered = filtered.filter(member => member.education === filterEducation.value);
      }
      
      return filtered.sort((a, b) => {
        if (a.generation !== b.generation) {
          return (a.generation || 0) - (b.generation || 0);
        }
        return a.name.localeCompare(b.name);
      });
    });
    
    // 方法
    const loadMembers = async () => {
      loading.value = true;
      try {
        const data = await getPersons();
        console.log('【调试】members数据', data);
        
        // 调试：检查王建国、王建华、王秀兰的父母关系
        const wangJianguo = data.find(m => m.name === '王建国');
        const wangJianhua = data.find(m => m.name === '王建华');
        const wangXiulan = data.find(m => m.name === '王秀兰');
        
        console.log('【调试】王建国父母关系:', {
          id: wangJianguo?.id,
          name: wangJianguo?.name,
          fatherId: wangJianguo?.fatherId,
          motherId: wangJianguo?.motherId,
          fatherIdType: typeof wangJianguo?.fatherId,
          motherIdType: typeof wangJianguo?.motherId
        });
        
        console.log('【调试】王建华父母关系:', {
          id: wangJianhua?.id,
          name: wangJianhua?.name,
          fatherId: wangJianhua?.fatherId,
          motherId: wangJianhua?.motherId,
          fatherIdType: typeof wangJianhua?.fatherId,
          motherIdType: typeof wangJianhua?.motherId
        });
        
        console.log('【调试】王秀兰父母关系:', {
          id: wangXiulan?.id,
          name: wangXiulan?.name,
          fatherId: wangXiulan?.fatherId,
          motherId: wangXiulan?.motherId,
          adoptedFatherId: wangXiulan?.adoptedFatherId,
          adoptedMotherId: wangXiulan?.adoptedMotherId,
          fatherIdType: typeof wangXiulan?.fatherId,
          motherIdType: typeof wangXiulan?.motherId
        });
        
        // 调试：查找所有父母是王老太爷和王老太太的子女
        const childrenOfWangOld = data.filter(m => 
          (m.fatherId == 1 && m.motherId == 2) || 
          (m.adoptedFatherId == 1 && m.adoptedMotherId == 2)
        );
        console.log('【调试】王老太爷和王老太太的所有子女:', childrenOfWangOld.map(c => ({
          id: c.id,
          name: c.name,
          fatherId: c.fatherId,
          motherId: c.motherId,
          adoptedFatherId: c.adoptedFatherId,
          adoptedMotherId: c.adoptedMotherId
        })));
        
        members.value = data;
      } catch (error) {
        console.error('加载成员失败:', error);
        // 如果API失败，使用默认数据
        members.value = [
          {
            id: 1,
            name: '赵小东',
            gender: '男',
            generation: 2,
            birthDate: '1980-01-01',
            children: [
              { id: 2, name: '王建华', gender: '女', generation: 3 },
              { id: 3, name: '赵强', gender: '男', generation: 3 },
              { id: 4, name: '王大山', gender: '男', generation: 2 } // 这个代际错误
            ],
            siblings: [
              { id: 5, name: '王老太爷', gender: '男', generation: 1 },
              { id: 6, name: '王老太太', gender: '女', generation: 1 },
              { id: 4, name: '王大山', gender: '男', generation: 2 }, // 重复数据
              { id: 7, name: '张秀英', gender: '女', generation: 2 }
            ]
          }
        ];
      } finally {
        loading.value = false;
      }
    };
    
    const refreshData = () => {
      loadMembers();
    };
    
    const filterMembers = () => {
      // 筛选逻辑已在computed中处理
    };
    
    const relatives = ref({});
    
    const selectMember = async (member) => {
      // 确保 member.id 是数字
      if (!member.id || isNaN(Number(member.id))) {
        alert('成员ID无效，无法获取家庭关系！');
        return;
      }
      try {
        const detail = await getPersonById(member.id);
        selectedMember.value = detail;
        relatives.value = await getRelatives(member.id);
      } catch (error) {
        console.error('获取成员详情失败:', error);
        selectedMember.value = member;
        relatives.value = {};
      }
    };
    
    const editMember = (member) => {
      editingMember.value = member;
      showAddForm.value = true;
    };
    
    const deleteMember = async (member) => {
      if (confirm(`确定要删除成员 "${member.name}" 吗？`)) {
        try {
          console.log(`【调试】开始删除成员: ${member.name} (ID: ${member.id})`);
          const result = await deletePerson(member.id);
          console.log(`【调试】删除结果:`, result);
          
          // 重新加载成员列表
          console.log(`【调试】重新加载成员列表`);
          await loadMembers();
          
          console.log(`【调试】删除完成，当前成员数量: ${members.value.length}`);
        } catch (error) {
          console.error('删除成员失败:', error);
          alert('删除失败：' + (error.message || error));
        }
      }
    };
    
    const handleSaveMember = async (memberData) => {
      try {
        if (editingMember.value) {
          await updatePerson(editingMember.value.id, memberData);
        } else {
          await createPerson(memberData);
        }
        
        await loadMembers();
        closeForm();
      } catch (error) {
        console.error('保存成员失败:', error);
        alert('保存失败：' + error.message);
      }
    };
    
    const closeForm = () => {
      showAddForm.value = false;
      editingMember.value = null;
    };
    
    const closeDetail = () => {
      selectedMember.value = null;
    };
    
    const handleError = (error) => {
      console.error('表单错误:', error);
      alert('操作失败：' + error.message);
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    };
    
    const toggleAdvancedFilters = () => {
      showAdvancedFilters.value = !showAdvancedFilters.value;
    };
    
    const clearAllFilters = () => {
      searchKeyword.value = '';
      filterGeneration.value = '';
      filterGender.value = '';
      filterOccupation.value = '';
      filterMaritalStatus.value = '';
      filterAgeMin.value = null;
      filterAgeMax.value = null;
      filterEducation.value = '';
      showAdvancedFilters.value = false;
    };
    
    const updateMemberPhotos = async (updatedPhotos) => {
      if (selectedMember.value) {
        try {
          // 更新本地状态
          selectedMember.value.photos = updatedPhotos;
          
          // 重新加载成员列表以确保数据同步
          await loadMembers();
          
          // 重新获取当前选中成员的详细信息
          const updatedMember = members.value.find(m => m.id === selectedMember.value.id);
          if (updatedMember) {
            selectedMember.value = updatedMember;
          }
        } catch (error) {
          console.error('更新照片失败:', error);
        }
      }
    };
    
    // 生命周期
    onMounted(() => {
      loadMembers();
    });
    
    watch(members, (val) => {
      if (activeTab.value === 'tree') {
        console.log('【家族树tab传入members】', val);
      }
    });
    
    const auth = useAuthStore();
    
    const showRecycleBin = ref(false);
    const deletedMembers = ref([]);
    const recycleBinLoading = ref(false);

    const loadDeletedMembers = async () => {
      recycleBinLoading.value = true;
      try {
        deletedMembers.value = await getDeletedPersons();
      } catch (e) {
        deletedMembers.value = [];
      } finally {
        recycleBinLoading.value = false;
      }
    };

    watch(showRecycleBin, (val) => {
      if (val) loadDeletedMembers();
    });

    const restoreDeletedMember = async (member) => {
      if (confirm(`确定要恢复成员 "${member.name}" 吗？`)) {
        await restorePerson(member.id);
        await loadMembers();
        await loadDeletedMembers();
      }
    };
    
    return {
      members,
      loading,
      showAddForm,
      editingMember,
      selectedMember,
      activeTab,
      activeDetailTab,
      searchKeyword,
      filterGeneration,
      filterGender,
      showAdvancedFilters,
      filterOccupation,
      filterMaritalStatus,
      filterAgeMin,
      filterAgeMax,
      filterEducation,
      tabs,
      detailTabs,
      availableGenerations,
      availableOccupations,
      availableEducations,
      filteredMembers,
      loadMembers,
      refreshData,
      filterMembers,
      selectMember,
      editMember,
      deleteMember,
      handleSaveMember,
      closeForm,
      closeDetail,
      handleError,
      formatDate,
      toggleAdvancedFilters,
      clearAllFilters,
      updateMemberPhotos,
      relatives,
      auth,
      showRecycleBin,
      deletedMembers,
      recycleBinLoading,
      restoreDeletedMember
    };
  }
};
</script>

<style scoped>
.family-tree-view {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.view-header {
  background-color: white;
  padding: 20px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.view-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.primary {
  background-color: #4CAF50;
  color: white;
}

.primary:hover {
  background-color: #45a049;
}

.secondary {
  background-color: #f4f4f4;
  color: #333;
  border: 1px solid #ddd;
}

.secondary:hover {
  background-color: #e7e7e7;
}

.view-tabs {
  background-color: white;
  border-bottom: 1px solid #ddd;
  display: flex;
  padding: 0 20px;
}

.tab-btn {
  padding: 15px 20px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.tab-btn:hover {
  color: #333;
  background-color: #f8f9fa;
}

.tab-btn.active {
  color: #4CAF50;
  border-bottom-color: #4CAF50;
}

.view-content {
  flex: 1;
  overflow: visible;
}

/* 列表视图 */
.list-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header {
  background-color: white;
  padding: 15px 20px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.basic-search {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 200px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 120px;
}

.advanced-filters {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 15px;
  margin-top: 10px;
}

.filter-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-group label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.age-input {
  width: 80px;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.filter-controls {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
  border-color: #6c757d;
}

.btn-secondary:hover {
  background-color: #5a6268;
  border-color: #545b62;
}

.member-count {
  color: #666;
  font-size: 14px;
}

.members-grid {
  flex: 1;
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  overflow-y: auto;
}

.member-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.member-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.member-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin-bottom: 15px;
}

.member-avatar.gender-男 {
  background-color: #2196F3;
}

.member-avatar.gender-女 {
  background-color: #E91E63;
}

.member-info {
  flex: 1;
}

.member-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #333;
}

.member-details {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.gender {
  font-weight: bold;
}

.generation {
  background-color: #e3f2fd;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.birth-date {
  color: #999;
}

.spouse-info {
  font-size: 12px;
  color: #999;
  font-style: italic;
  margin-bottom: 8px;
}

.spouse-name {
  font-weight: bold;
}

.children-info {
  font-size: 12px;
  color: #999;
  font-style: italic;
  margin-bottom: 8px;
}

.children-count {
  font-weight: bold;
}

.occupation {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.description {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.member-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
}

.action-btn {
  width: 30px;
  height: 30px;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.action-btn.edit {
  background-color: #FFC107;
  color: white;
}

.action-btn.edit:hover {
  background-color: #FFB300;
}

.action-btn.delete {
  background-color: #F44336;
  color: white;
}

.action-btn.delete:hover {
  background-color: #D32F2F;
}

/* 树视图和网络视图 */
.tree-view,
.network-view {
  min-height: 100%;
}

/* 统计视图 */
.stats-view {
  height: 100%;
  overflow-y: auto;
}

/* 成员详情弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  max-width: 800px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.detail-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.tab-btn {
  padding: 10px 20px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.2s ease;
}

.tab-btn:hover {
  color: #007bff;
}

.tab-btn.active {
  color: #007bff;
  border-bottom-color: #007bff;
}

.detail-content {
  min-height: 300px;
}

.member-detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.detail-item span,
.detail-item p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.family-relations {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.relation-group h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.relation-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.relation-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.relation-item:hover {
  border-color: #007bff;
  background-color: #f8f9fa;
}

.member-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 16px;
}

.member-avatar.男 {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
}

.member-avatar.女 {
  background: linear-gradient(135deg, #e83e8c 0%, #c73e6b 100%);
}

.relation-info {
  flex: 1;
}

.relation-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.relation-detail {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

@media (max-width: 768px) {
  .view-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .view-tabs {
    overflow-x: auto;
  }
  
  .list-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-filter {
    flex-direction: column;
  }
  
  .search-input {
    width: 100%;
  }
  
  .members-grid {
    grid-template-columns: 1fr;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .modal-content {
    width: 95%;
    margin: 10px;
  }
}

.btn.danger {
  background-color: #e74c3c;
  color: #fff;
}
.btn.danger:hover {
  background-color: #c0392b;
}
.recycle-list {
  list-style: none;
  padding: 0;
}
.recycle-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}
.btn.restore {
  background-color: #27ae60;
  color: #fff;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}
.btn.restore:hover {
  background-color: #219150;
}
</style>